package eu.codlab.twitteirb;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import eu.codlab.twitteirb.manage.SendTweetListener;
import eu.codlab.twitteirb.manage.url.LoadURL;

import android.content.Context;
import android.os.AsyncTask;
//import android.util.Log;

public final class SendTweet {
	private TwittEirbService _master;
	private Context _context;
	private String _last;
	private String _cookie;
	private SendTweetListener _send_tweet;
	private String _text;

	private SendTweet(){
		_last = null;
	}

	public SendTweet(Context context,String text, SendTweetListener sendtweet,String cookie){
		this();
		_send_tweet = sendtweet;
		_cookie = cookie;
		_text=text;
		_context = context;
	}

	public void setLastId(String last){
		_last =last;
	}

	private final class MessageAsync extends AsyncTask<URL, Object, Object>{
		private MessageAsync(){

		}

		@Override
		protected Integer doInBackground(URL... arg0) {
			try{

				String[] headers=new String[]{
						"Host","twitt.eirb.fr",
						"User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1",
						"Accept","*/*",
						"Accept-Language","fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3",
						"Accept-Encoding","gzip, deflate",
						"Connection","keep-alive",
						"X-Requested-With","XMLHttpRequest",
						"Referer","http://twitt.eirb.fr/",
						"Cookie",_cookie+";",
						"Pragma","no-cache",
						"Cache-Control","no-cache"
				};
				
				//for(int i=0;i<headers.length;i+=2)
					//Log.d(headers[i],headers[i+1]);
				List<BasicNameValuePair> _list = new ArrayList<BasicNameValuePair>();
				try {
					_list.add(new BasicNameValuePair("tweet",_text));
				} catch (Exception e) {
					e.printStackTrace();
				}
				LoadURL chargement = new LoadURL("http://twitt.eirb.fr/post_tweet.php");
				chargement.loadPostUrl(headers, _list);
				_send_tweet.onTweetSend();
				/*if (!url.getHost().equals(urlConnection.getURL().getHost())) {
					_master.onGetMessageRedirect();
				}else{
					_master.onGetMessageString(readStream(in));
				}*/
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

	}

	public void go(){
		URL url=null;
		try {

			url = new URL("http://twitt.eirb.fr/?ajax&minid="+_last);
			MessageAsync m = new MessageAsync();
			URL[] u = new URL[1];
			u[0]=url;
			m.execute(u);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
